package com.cy.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.cy.common.Constant;
import com.cy.entity.LoginTicket;
import com.cy.entity.User;
import com.cy.mapper.UserMapper;
import com.cy.service.LoginTicketService;
import com.cy.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cy.util.CommunityUtil;
import com.cy.util.MailClient;
import com.cy.util.RedisKeyUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import sun.util.resources.LocaleData;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author cy
 * @since 2021-11-08
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private MailClient mailClient;

    @Resource
    private TemplateEngine templateEngine;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private UserService userService;

//    @Resource
//    private LoginTicketService loginTicketService;

    @Value("${community.path.domain}")
    private String domain;

    @Value("${server.servlet.context-path}")
    private String contextPath;


    public User findUserById(int userId){
        User user = getCache(userId);
        if(user == null){
            user = initCache(userId);
        }
        return user;
    }


    public Map<String, Object> register(User user) {
        HashMap<String, Object> map = new HashMap<>();

        if (user == null) {
            throw new IllegalArgumentException("参数不能为空");
        }
        if (StrUtil.isBlank(user.getUsername())) {
            map.put("usernameMsg", "账号不能为空");
            return map;
        }
        if (StrUtil.isBlank(user.getPassword())) {
            map.put("passwordMsg", "密码不能为空");
            return map;
        }
        if (StrUtil.isBlank(user.getEmail())) {
            map.put("emailMsg", "邮箱不能为空");
            return map;
        }

        //验证账号
        QueryWrapper<User> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("username", user.getUsername());
        if (this.baseMapper.selectCount(wrapper1) > 0) {
            map.put("usernameMsg", "该账号已存在");
            return map;
        }

        //验证邮箱
        QueryWrapper<User> wrapper2 = new QueryWrapper<>();
        wrapper2.eq("email", user.getEmail());
        if (this.baseMapper.selectCount(wrapper2) > 0) {
            map.put("emailMsg", "该邮箱已存在");
            return map;
        }

        //注册用户
        user.setSalt(CommunityUtil.generateUUID().substring(0, 5));
        user.setPassword(CommunityUtil.md5(user.getPassword() + user.getSalt()));  //密码进行md5+随机盐加密
        user.setType(Constant.GENERAL_USER);    //默认普通用户
        user.setStatus(Constant.NOT_ACTIVE);    //默认未激活
        user.setActivationCode(CommunityUtil.generateUUID());
        user.setHeaderUrl(String.format("https://images.nowcoder.com/head/%dt.png", new Random().nextInt(1000)));
        user.setCreateTime(new Date());
        int flog = this.baseMapper.insert(user);

        //发送激活邮件
        if (flog > 0) {
            Context context = new Context();
            context.setVariable("email", user.getEmail());

            // http://localhost:8080/community/activation/101/code
            String url = domain + contextPath + "/activation/" + user.getId() + "/" + user.getActivationCode();
            context.setVariable("url", url);
            String content = templateEngine.process("/mail/activation", context);
            mailClient.sendMail(user.getEmail(), "激活账号", content, true);
        }
        return map;
    }


    @Override
    public int activation(String userId, String code) {
        // http://localhost:8080/community/activation/101/code
        User user = this.baseMapper.selectById(userId);
        if(user != null){
            if(user.getStatus() == Constant.ACTIVE){
                return Constant.ACTIVATION_REPEAT;      //重复激活
            }else if(user.getActivationCode().equals(code)){
                User u = this.baseMapper.selectById(userId);
                u.setStatus(1);
                this.baseMapper.updateById(u);

                clearCache(Integer.valueOf(userId));

                return Constant.ACTIVATION_SUCCESS;     //激活成功
            }else {
                return Constant.ACTIVATION_FAIL;        //激活失败
            }
        }
        return Constant.ACTIVATION_FAIL;              //激活失败
    }


    /**
     * 登录
     * @param username
     * @param password
     * @param expiredSeconds
     * @return
     */
    public Map<String, Object> login(String username, String password, int expiredSeconds) {
        Map<String, Object> map = new HashMap<>();

        // 空值处理
        if (StringUtils.isBlank(username)) {
            map.put("usernameMsg", "账号不能为空!");
            return map;
        }
        if (StringUtils.isBlank(password)) {
            map.put("passwordMsg", "密码不能为空!");
            return map;
        }

        // 验证账号
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        User user = this.baseMapper.selectOne(wrapper);
        if (user == null) {
            map.put("usernameMsg", "该账号不存在!");
            return map;
        }

        // 验证状态
        if (user.getStatus() == 0) {
            map.put("usernameMsg", "该账号未激活!");
            return map;
        }

        // 验证密码
        password = CommunityUtil.md5(password + user.getSalt());
        if (!user.getPassword().equals(password)) {
            map.put("passwordMsg", "密码不正确!");
            return map;
        }

        // 生成登录凭证
        LoginTicket loginTicket = new LoginTicket();
        loginTicket.setUserId(user.getId());
        loginTicket.setTicket(CommunityUtil.generateUUID());
        loginTicket.setStatus(Constant.LOGIN_TICKET_CAN_USE);
        loginTicket.setExpired(new Date(System.currentTimeMillis() + expiredSeconds * 1000));
//        loginTicketService.save(loginTicket);

        String redisKey = RedisKeyUtil.getTicketKey(loginTicket.getTicket());
        redisTemplate.opsForValue().set(redisKey, loginTicket);

        map.put("ticket", loginTicket.getTicket());
        return map;
    }


    /**
     * 退出登录
     * @param ticket   登录凭证
     * @return
     */
    @Override
    public Boolean logout(String ticket) {
        if(StrUtil.isNotBlank(ticket)){
            String redisKey = RedisKeyUtil.getTicketKey(ticket);
            LoginTicket loginTicket = (LoginTicket) redisTemplate.opsForValue().get(redisKey);
            loginTicket.setStatus(1);   //1代表无效
            redisTemplate.opsForValue().set(redisKey, loginTicket);
        }
        return true;
    }

    @Override
    public Boolean updateHeader(Integer id, String headerUrl) {
        if(StrUtil.isNotBlank(id+"") && StrUtil.isNotBlank(headerUrl)){
            User user = this.baseMapper.selectById(id);
            if (user != null) {
                user.setHeaderUrl(headerUrl);
                int rows = this.baseMapper.updateById(user);
                clearCache(id);
                return rows>0;
            }
        }
        return false;
    }



    // 1.从缓存中获取数据
    private User getCache(int userId){
        String redisKey = RedisKeyUtil.getUserKey(userId);
        return (User) redisTemplate.opsForValue().get(redisKey);
    }

    // 2.取不到时初始缓存数据
    private User initCache(int userId){
        User user = userService.getById(userId);
        String redisKey = RedisKeyUtil.getUserKey(user.getId());
        redisTemplate.opsForValue().set(redisKey, user, 1, TimeUnit.HOURS);
        return user;
    }

    // 3.数据变更时清除缓存数据
    private void clearCache(int userId){
        String redisKey = RedisKeyUtil.getUserKey(userId);
        redisTemplate.delete(redisKey);
    }


    // 根据用户id获取其角色信息
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities(int userId) {
        User user = this.findUserById(userId);

        List<GrantedAuthority> list = new ArrayList<>();
        list.add(new GrantedAuthority() {

            @Override
            public String getAuthority() {
                switch (user.getType()) {
                    case 1:
                        return Constant.AUTHORITY_ADMIN;
                    case 2:
                        return Constant.AUTHORITY_MODERATOR;
                    default:
                        return Constant.AUTHORITY_USER;
                }
            }
        });
        return list;
    }


}
